﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using VietImage.Models;
using VietImage.Supports;
using VietImage.Roles;
using System.IO;

namespace VietImageSoftware
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private ReadXMLHelper xmlHelper;

        internal ReadXMLHelper XmlHelper
        {
            get { return xmlHelper; }
            set { xmlHelper = value; }
        }

        private RegisteredUserRole userRole;

        public RegisteredUserRole UserRole
        {
            get { return userRole; }
            set { userRole = value; }
        }

        ImageSource ibExit;
        ImageSource ibMinimize;
        ImageSource ibHoverExit;
        ImageSource ibHoverMinimize;
        List<ErrorItem> errorList;
        int currentPage;
        int countPages;
        int countImages;
        private VietImage.Models.Image currentImage;
        System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Status> omStatuses = new System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Status>();
        System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image> omUploadedImages = new System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image>();
        System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image> omHistoryImages = new System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image>();

        List<VietImage.Models.Image> lHistoryImages = new List<VietImage.Models.Image>();

        public List<VietImage.Models.Image> LHistoryImages
        {
            get { return lHistoryImages; }
            set { lHistoryImages = value; }
        }

        public System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image> OmUploadedImages
        {
            get { return omUploadedImages; }
        }
        public System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Image> OmHistoryImages
        {
            get { return omHistoryImages; }
        }
        public System.Collections.ObjectModel.ObservableCollection<VietImage.Models.Status> OmStatuses
        {
            get { return omStatuses; }
        }

        public MainWindow()
        {

            this.userRole = new RegisteredUserRole();
            ibExit = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "Images/Button/circle_exit.png", UriKind.Relative));
            ibHoverExit = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "Images/Button/circle_exit_hover.png", UriKind.Relative));
            ibMinimize = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "Images/Button/circle_mini.png", UriKind.Relative));
            ibHoverMinimize = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "Images/Button/circle_mini_hover.png", UriKind.Relative));

            InitializeComponent();
            foreach (VietImage.Models.Language i in VietImage.Models.Language.GetList())
                cbMainLanguage.Items.Add(i);
            cbMainLanguage.SelectedValuePath = "ID";
            cbMainLanguage.DisplayMemberPath = "Language1";
        }

        #region MainWindow


        private void mainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            xmlHelper = new ReadXMLHelper();
            xmlHelper.ReadXML();
            txtLIUsername.Text = xmlHelper.Username;
        }

        private void mainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            xmlHelper.WriteXML();
        }

        private void gridMain_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            for (int i = 0; i < cbMainLanguage.Items.Count; i++)
            {
                VietImage.Models.Language l = (VietImage.Models.Language)cbMainLanguage.Items[i];
                if (l.ID == xmlHelper.Language)
                {
                    cbMainLanguage.SelectedIndex = i;
                    break;
                }
            }
        }

        private void cbMainLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbMainLanguage.SelectedIndex >= 0)
            {
                int lang = int.Parse(cbMainLanguage.SelectedValue.ToString());
                xmlHelper.Language = lang;
                userRole.ID_Language = lang;
                omStatuses.Clear();
                foreach (VietImage.Models.Status i in VietImage.Models.Status.GetList())
                    if (i.ID_Language == userRole.ID_Language)
                        omStatuses.Add(i);
                cbHStatus.ItemsSource = omStatuses;
                cbUIStatus.ItemsSource = omStatuses;
                InitCategoryList(true);
                InitCategoryList(false);
                currentPage = 1;
                if (gridHistory.IsVisible && userRole.UserInfo != null)
                {
                    new Thread(
                        delegate()
                        {
                            LoadImagesList(userRole.UserInfo.ID_Permission);
                        }).Start();
                }
                else if (gridUploadImages.IsVisible && userRole.UserInfo != null && currentCategory != null)
                {
                    new Thread(
                        delegate()
                        {
                            LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                        }).Start();
                }
            }
        }

        private void gdMain_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch (Exception ex)
            {
            }
        }

        private void cMinimize_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ImageBrush temp = (ImageBrush)cMinimize.Background;
            temp.ImageSource = ibHoverMinimize;
        }

        private void cExit_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ImageBrush temp = (ImageBrush)cExit.Background;
            temp.ImageSource = ibHoverExit;
        }

        private void cExit_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ImageBrush temp = (ImageBrush)cExit.Background;
            temp.ImageSource = ibExit;
        }

        private void cMinimize_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ImageBrush temp = (ImageBrush)cMinimize.Background;
            temp.ImageSource = ibMinimize;
        }

        private void cExit_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Close();
        }

        private void cMinimize_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void cCategory_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            gridProfile.Visibility = Visibility.Hidden;
            gridCategory.Visibility = Visibility.Visible;
            gridUploadImages.Visibility = Visibility.Hidden;
            gridHistory.Visibility = Visibility.Hidden;
            gridAboutUs.Visibility = Visibility.Hidden;
            txbWelcome.Visibility = Visibility.Hidden;
        }

        private void cProfile_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            gridProfile.Visibility = Visibility.Visible;
            gridCategory.Visibility = Visibility.Hidden;
            gridUploadImages.Visibility = Visibility.Hidden;
            gridHistory.Visibility = Visibility.Hidden;
            gridAboutUs.Visibility = Visibility.Hidden;
            txbWelcome.Visibility = Visibility.Hidden;
        }

        private void cImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            gridProfile.Visibility = Visibility.Hidden;
            gridCategory.Visibility = Visibility.Hidden;
            gridUploadImages.Visibility = Visibility.Visible;
            gridHistory.Visibility = Visibility.Hidden;
            gridAboutUs.Visibility = Visibility.Hidden;
            txbWelcome.Visibility = Visibility.Hidden;
        }

        private void cHistory_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            gridProfile.Visibility = Visibility.Hidden;
            gridCategory.Visibility = Visibility.Hidden;
            gridUploadImages.Visibility = Visibility.Hidden;
            gridHistory.Visibility = Visibility.Visible;
            gridAboutUs.Visibility = Visibility.Hidden;
            txbWelcome.Visibility = Visibility.Hidden;
        }

        private void cAboutUs_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            gridProfile.Visibility = Visibility.Hidden;
            gridCategory.Visibility = Visibility.Hidden;
            gridUploadImages.Visibility = Visibility.Hidden;
            gridHistory.Visibility = Visibility.Hidden;
            gridAboutUs.Visibility = Visibility.Visible;
            txbWelcome.Visibility = Visibility.Hidden;
        }
        #endregion

        #region Login
        private void gridLogin_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            try
            {
                this.DragMove();
            }
            catch (Exception ex)
            {
            }
        }
        private void btnLILogin_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //userRole.UserInfo = User.GetUser(1);
            //userRole.UserInfo.Password = VietImage.Helpers.Encoder.MD5Encode("123456");
            //User.ChangeInformation(userRole.UserInfo, 1, 1);
            if (userRole.Login(txtLIUsername.Text, txtLIPassword.Password))
            {
                if (userRole.UserInfo.ID_Permission == 1)
                {
                    OwnerRole owner = new OwnerRole();
                    owner.UserInfo = userRole.UserInfo;
                    owner.ID_Language = userRole.ID_Language;
                    userRole = owner;
                    gridLogin.Visibility = Visibility.Hidden;
                    gridMain.Visibility = Visibility.Visible;
                    xmlHelper.Username = txtLIUsername.Text;
                    xmlHelper.WriteXML();
                }
                else if (userRole.UserInfo.ID_Permission == 4)
                {
                    PartnerRole partner = new PartnerRole();
                    partner.UserInfo = userRole.UserInfo;
                    partner.ID_Language = userRole.ID_Language;
                    userRole = partner;
                    //cCategory.IsEnabled = false;
                    //btnUINew.Visibility = Visibility.Hidden;
                    //btnUINewSub.Visibility = Visibility.Hidden;
                    //gridLogin.Visibility = Visibility.Hidden;
                    //gridMain.Visibility = Visibility.Visible;
                    cbMainLanguage.SelectedIndex = 0;
                    gridLogin.Visibility = Visibility.Hidden;
                    gridMain.Visibility = Visibility.Visible;
                    cCategory.IsEnabled = false;
                    cCategory.ToolTip = "Just for Owner";
                    btnUINew.IsEnabled = false;
                    btnUINew.ToolTip = "Just for Owner";
                    xmlHelper.Username = txtLIUsername.Text;
                    xmlHelper.WriteXML();
                }
                else
                {
                    MessageForm form = new MessageForm();
                    form.UserRole = userRole;
                    form.HaveOKButton = false;
                    form.TxtTitle = "Warning";
                    form.TxtMessage = "Access denied! You don't have permission to use this application!";
                    form.TxtCancel = "Cancel";
                    form.ShowDialog();
                }
            }
            else
            {
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = false;
                form.TxtTitle = "Error";
                form.TxtMessage = "Wrong username or password !";
                form.TxtCancel = "Cancel";
                form.ShowDialog();
            }
        }

        private void btnLICancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }

        private void btnLIRegister_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        }
        #endregion

        #region My Account

        private void btnChange_Click(object sender, RoutedEventArgs e)
        {
            errorList = new List<ErrorItem>();
            string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" +
               @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" +
               @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
            System.Text.RegularExpressions.Match match =
                System.Text.RegularExpressions.Regex.Match(txtMAEmail.Text.Trim(), 
                    pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (txtMAEmail.Text != "" && !match.Success)
            {
                errorList.Add(new ErrorItem("ErrorMessage", "Please enter a valid email!"));
                if (errorList.Count > 0)
                {
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                    return;
                }
            }
            if (txtMACellfone.Text != userRole.UserInfo.Cellfone || txtMAEmail.Text != userRole.UserInfo.Cellfone)
            {
                User i = userRole.UserInfo.Clone();
                i.Cellfone = txtMACellfone.Text;
                i.Email = txtMAEmail.Text;

                if (rbMAMale.IsChecked.Value)
                    i.Gender = 1;
                else
                    i.Gender = 0;

                errorList = userRole.ChangeUserInformation(i, null);
                if (errorList.Count > 0)
                {
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                }
            }
            if (txtMANewPassword.Password != "" || txtMAOldPassword.Password != "" || txtMARetypeNewPassword.Password != "")
            {
                if (txtMANewPassword.Password == txtMARetypeNewPassword.Password && txtMANewPassword.Password.Trim() != "" && VietImage.Helpers.Encoder.MD5Encode(txtMAOldPassword.Password) == userRole.UserInfo.Password)
                {
                    User i = userRole.UserInfo.Clone();
                    i.Password = VietImage.Helpers.Encoder.MD5Encode(txtMANewPassword.Password);
                    errorList = userRole.ChangeUserInformation(i, null);
                    if (errorList.Count > 0)
                    {
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                }
                else
                {
                    errorList.Add(new ErrorItem("ErrorMessage", "Wrong password"));
                    if (errorList.Count > 0)
                    {
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                }
            }

            if (errorList.Count == 0)
            {
                userRole.UserInfo = User.GetUser(userRole.UserInfo.ID);
                errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));
                MessageForm form = new MessageForm();
                form.ErrorList = errorList;
                form.ShowDialog();
            }
            ResetFormMyAccount();
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            ResetFormMyAccount();
        }

        private void ResetFormMyAccount()
        {
            dpMABirthday.SelectedDate = userRole.UserInfo.Birthday;
            txtMACellfone.Text = userRole.UserInfo.Cellfone;
            txtMAEmail.Text = userRole.UserInfo.Email;
            txtMANewPassword.Password = "";
            txtMAOldPassword.Password = "";
            txtMARetypeNewPassword.Password = "";
            txtMAUsername.Text = userRole.UserInfo.Username;
            if (userRole.UserInfo.Gender == 1)
                rbMAMale.IsChecked = true;
            else
                rbMAFemale.IsChecked = true;
        }

        private void gridProfile_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (gridProfile.IsVisible)
                ResetFormMyAccount();

        }
        #endregion

        #region Category Manager
        private void btnCNew_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ManageCategoryForm form = new ManageCategoryForm();
            form.UserRole = userRole;
            form.TxtTitle = "Create category";
            form.TxtManage = "Create";
            form.ShowDialog();
            InitCategoryList(true);
        }

        private void btnCEdit_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (lbCCategory.SelectedIndex >= 0)
            {
                ManageCategoryForm form = new ManageCategoryForm();
                form.UserRole = userRole;
                form.TxtTitle = "Edit category";
                form.TxtManage = "Edit";
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
                InitCategoryList(true);
            }
            else if (lbCSubCategory.SelectedIndex >= 0)
            {
                ManageCategoryForm form = new ManageCategoryForm();
                form.UserRole = userRole;
                form.TxtTitle = "Edit sub category";
                form.TxtManage = "Edit";
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
                InitCategoryList(true);
            }
            else
            {
                errorList = new List<ErrorItem>();
                errorList.Add(new ErrorItem("Warning", "Please choose category."));
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose category!";
                form.ShowDialog();
            }
        }

        private void btnCNewSub_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (lbCCategory.SelectedIndex >= 0 || cbUICategory.SelectedIndex >= 0)
            {
                ManageCategoryForm form = new ManageCategoryForm();
                form.UserRole = userRole;
                form.TxtTitle = "Create sub category";
                form.TxtManage = "Create";
                if (currentCategory.IsParent)
                    form.ParentCategory = currentCategory;
                else if (cbUICategory.SelectedIndex >= 0)
                    form.ParentCategory = ((DetailCategory)cbUICategory.SelectedItem).Category;
                form.ShowDialog();
                InitCategoryList(true);
            }
            else
            {
                errorList = new List<ErrorItem>();
                errorList.Add(new ErrorItem("Warning", "Please choose category."));
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose category!";
                form.ShowDialog();
            }
        }

        private void btnCDelete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentCategory != null)
            {
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = true;
                form.TxtOK = "Yes";
                form.TxtCancel = "No";
                form.TxtTitle = "Warning";
                if (currentCategory.IsParent)
                    form.TxtMessage = "If you delete this category, all image and sub-categories in it will be deleted too! Do you want to delete the category?";
                else
                    form.TxtMessage = "If you delete this category, all images in it will be deleted too! Do you want to delete the category?";
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
                InitCategoryList(true);
            }
            else
            {
                errorList = new List<ErrorItem>();
                errorList.Add(new ErrorItem("Warning", "Please choose category."));
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose category!";
                form.ShowDialog();
            }
        }

        private void InitCategoryList(bool isListbox)
        {
            if (userRole == null)
                return;
            List<Category> l = null;
            l = userRole.ViewListAvailableParentCategories();
            if (l != null)
            {
                if (isListbox)
                {
                    lbCCategory.Items.Clear();
                    foreach (Category c in l)
                    {
                        if (c.IsParent)
                        {
                            DetailCategory dc = c.GetDetail(int.Parse(cbMainLanguage.SelectedValue.ToString()));
                            lbCCategory.Items.Add(dc);
                        }
                    }
                    lbCCategory.SelectedValuePath = "ID_Category";
                    lbCCategory.DisplayMemberPath = "Name";
                    if (lbCCategory.Items.Count > 0)
                        lbCCategory.SelectedIndex = 0;
                }
                else
                {
                    cbUICategory.Items.Clear();
                    foreach (Category c in l)
                    {
                        if (c.IsParent)
                        {
                            DetailCategory dc = c.GetDetail(int.Parse(cbMainLanguage.SelectedValue.ToString()));
                            cbUICategory.Items.Add(dc);
                        }
                    }
                    cbUICategory.SelectedValuePath = "ID_Category";
                    cbUICategory.DisplayMemberPath = "Name";
                    if (cbUICategory.Items.Count > 0)
                        cbUICategory.SelectedIndex = 0;
                }
            }
        }

        private void gridCategory_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (gridCategory.IsVisible)
            {
                InitCategoryList(true);
            }
        }

        private void lbCCategory_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (lbCCategory.SelectedIndex >= 0)
            {
                lbCSubCategory.SelectedIndex = -1;
                DetailCategory c = (DetailCategory)lbCCategory.SelectedItem;
                currentCategory = c.Category;
                List<Category> dl = currentCategory.GetListAvailableChildren();
                lbCSubCategory.Items.Clear();
                if (dl != null)
                {
                    foreach (Category temp in dl)
                    {
                        if (!temp.IsParent)
                        {
                            DetailCategory dc = temp.GetDetail(int.Parse(cbMainLanguage.SelectedValue.ToString()));
                            lbCSubCategory.Items.Add(dc);
                        }
                    }
                    lbCSubCategory.SelectedValuePath = "ID_Category";
                    lbCSubCategory.DisplayMemberPath = "Name";
                }
            }
        }

        private void lbCSubCategory_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (lbCSubCategory.SelectedIndex >= 0)
            {
                lbCCategory.SelectedIndex = -1;
                DetailCategory c = (DetailCategory)lbCSubCategory.SelectedItem;
                currentCategory = c.Category;
            }
        }

        private void btnMCChooseParentCategories_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }

        private void btnCChoosePrimaryImage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (currentCategory != null)
            {
                ChoosePrimaryImageForm form = new ChoosePrimaryImageForm();
                form.UserRole = userRole;
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
            }
        }
        #endregion

        #region Upload Image
        Category currentCategory;
        private List<VietImage.Models.Image> lUploadImages;
        string[] lnUploadImages;

        private void btnLast_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            new Thread(
                    delegate()
                    {
                        //if (form.IsOK)
                        //    Update();

                        if (gridUploadImages.IsVisible)
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                            {
                                currentPage = countPages;
                                LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                                ((Button)sender).IsEnabled = false;
                                btnUIFirst.IsEnabled = true;
                            });
                        }
                        else
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                           {
                               currentPage = countPages;
                               LoadImagesList(userRole.UserInfo.ID_Permission);
                               ((Button)sender).IsEnabled = false;
                               btnHFirst.IsEnabled = true;
                           });
                        }
                    }).Start();
        }

        private void btnFirst_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            new Thread(
                    delegate()
                    {
                        //if (form.IsOK)
                        //    Update();
                        if (gridUploadImages.IsVisible)
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                            {
                                currentPage = 1;
                                LoadImagesList(userRole.UserInfo.ID_Permission, (currentCategory.ID));
                                ((Button)sender).IsEnabled = false;
                                btnUILast.IsEnabled = true;
                            });
                        }
                        else
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                            {
                                currentPage = 1;
                                LoadImagesList(userRole.UserInfo.ID_Permission);
                                ((Button)sender).IsEnabled = false;
                                btnHLast.IsEnabled = true;
                            });
                        }
                    }).Start();
        }

        private void btnNext(object sender, System.Windows.RoutedEventArgs e)
        {
            //MessageForm form = new MessageForm();
            //form.CurrentImage = currentImage;
            //form.UserRole = userRole;
            //form.HaveOKButton = true;
            //form.TxtOK = "Yes";
            //form.TxtCancel = "No";
            //form.TxtTitle = "Warning";
            //form.TxtMessage = "Do you want to change those images?";
            //form.ShowDialog();
            new Thread(
                    delegate()
                    {
                        //if (form.IsOK)
                        //    Update();

                        if (gridUploadImages.IsVisible)
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                           {
                               currentPage++;
                               LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                               btnUIPrev.IsEnabled = true;
                               if (currentPage == countPages)
                               {
                                   ((Button)sender).IsEnabled = false;
                                   btnUIFirst.IsEnabled = false;
                               }
                               btnUILast.IsEnabled = true;
                           });
                        }
                        else
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                           {
                               currentPage++;
                               LoadImagesList(userRole.UserInfo.ID_Permission);
                               btnHPrev.IsEnabled = true;
                               if (currentPage == countPages)
                               {
                                   ((Button)sender).IsEnabled = false;
                                   btnHFirst.IsEnabled = false;
                               }
                               btnHLast.IsEnabled = true;
                           });
                        }
                    }).Start();
        }

        private void btnPrev(object sender, System.Windows.RoutedEventArgs e)
        {
            //MessageForm form = new MessageForm();
            //form.CurrentImage = currentImage;
            //form.UserRole = userRole;
            //form.HaveOKButton = true;
            //form.TxtOK = "Yes";
            //form.TxtCancel = "No";
            //form.TxtTitle = "Warning";
            //form.TxtMessage = "Do you want to change those images?";
            //form.ShowDialog();
            new Thread(
                    delegate()
                    {
                        //if (form.IsOK)
                        //    Update();
                        if (gridUploadImages.IsVisible)
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                            {
                                currentPage--;
                                LoadImagesList(userRole.UserInfo.ID_Permission, (currentCategory.ID));
                                btnUINext.IsEnabled = true;
                                if (currentPage == 1)
                                {
                                    ((Button)sender).IsEnabled = false;
                                    btnUIFirst.IsEnabled = false;
                                }
                                btnUILast.IsEnabled = true;
                            });
                        }
                        else
                        {
                            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                            {
                                currentPage--;
                                LoadImagesList(userRole.UserInfo.ID_Permission);
                                btnHNext.IsEnabled = true;
                                if (currentPage == 1)
                                {
                                    ((Button)sender).IsEnabled = false;
                                    btnHFirst.IsEnabled = false;
                                }
                                btnHLast.IsEnabled = true;
                            });
                        }
                    }).Start();
        }

        //if (errorList.Count == 0)
        //   {
        //       errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));

        //   }
        //   else
        //       GetErrorList(errorList);

        private void btnEditDetailImage(object sender, System.Windows.RoutedEventArgs e)
        {
            //if (dgUIImagesList.SelectedIndex >= 0)
            //{
            //    ManageImageForm form = new ManageImageForm();
            //    form.CurrentImage = ((DetailImage)dgUIImagesList.SelectedItem).Image.Clone();
            //}
        }

        private void btnUIBrowse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.Multiselect = true;
            dialog.Filter = "JPEG (*.jpg;*.jpeg;*.jpe)|*.jpg;*.jpeg;*.jpe|" +
                                "BMP (*.bmp)|*.bmp|" +
                                "PNG (*.png)|*.png";
            dialog.AddExtension = true;
            dialog.Title = "Choose your images to upload";
            dialog.ShowReadOnly = true;
            dialog.CheckFileExists = true;
            dialog.ShowDialog();
            if (dialog.FileName != "")
            {
                lUploadImages = new List<VietImage.Models.Image>();
                lblUIUploading.Content = "Reading...";
                pbUIUpload.Minimum = 0;
                pbUIUpload.Maximum = dialog.FileNames.Count();
                pbUIUpload.Value = 0;
                lnUploadImages = dialog.FileNames;
                txtUIImages.Text = "";
                new Thread(
                       delegate()
                       {
                           Browse();
                       }).Start();
            }
        }

        private void Browse()
        {
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.IsEnabled = false; }, null);
            double value = 0;
            foreach (string img in lnUploadImages)
            {
                VietImage.Models.Image image = new VietImage.Models.Image();
                System.Drawing.Image i = System.Drawing.Image.FromFile(img);
                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                image.Source = (byte[])converter.ConvertTo(i, typeof(byte[]));
                image.TakenTime = DateTime.Now;
                foreach (System.Drawing.Imaging.ImageCodecInfo info in System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders())
                    if (info.FormatID == i.RawFormat.Guid)
                        image.ImageType = info.MimeType;
                lUploadImages.Add(image);
                String str = "";
                int begin = img.LastIndexOf('\\');
                str = img.Substring(begin + 1);
                Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtUIImages.SetValue(TextBox.TextProperty, txtUIImages.Text + "\"" + str + "\" ; "); }, null);
                value++;
                Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
            }
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Finish"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.IsEnabled = true; }, null);
        }

        private void btnUIEditDetail_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (dgUIImagesList.SelectedIndex >= 0)
            {
                currentImage = ((VietImage.Models.Image)dgUIImagesList.SelectedItem).Clone();
                ManageImageForm form = new ManageImageForm();
                form.UserRole = userRole;
                form.CurrentImage = currentImage;
                form.SubCategoryName = cbUISubCategory.Text;
                form.ShowDialog();
            }
            else
            {
                errorList = new List<ErrorItem>();
                MessageForm form = new MessageForm();
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose image";
                form.ShowDialog();
            }
        }

        private void gridUploadImages_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (gridUploadImages.IsVisible)
            {

                if (userRole.UserInfo.ID_Permission == 1)
                {
                    btnUINew.IsEnabled = true;
                    btnUINewSub.IsEnabled = true;
                }
                else
                {
                    btnUINew.IsEnabled = false;
                    btnUINewSub.IsEnabled = true;
                }

                lblUIUploading.Content = "";
                pbUIUpload.Value = 0;

                if (lnUploadImages != null)
                    if (lnUploadImages.Count() != 0)
                        btnUIUpload.IsEnabled = true;
                    else
                        btnUIUpload.IsEnabled = false;
                else
                    btnUIUpload.IsEnabled = false;

                InitCategoryList(false);
            }
        }


        private void LoadImagesList(int id_Permission, int id_Category)
        {
            new Thread(
                delegate()
                {
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                    {
                        ProgressBarForm form = new ProgressBarForm();
                        form.CurrentPage = currentPage;
                        form.UserRole = userRole;
                        form.CurrentCategory = currentCategory;
                        form.Id_Command = 7;
                        form.ShowDialog();
                        omUploadedImages = form.OmUploadedImages;
                        dgUIImagesList.ItemsSource = omUploadedImages;
                        countPages = form.CountPages;
                        countImages = form.CountImages;
                        if (omUploadedImages.Count != 0)
                        {
                            btnUINext.IsEnabled = true;
                            btnUIPrev.IsEnabled = true;
                            btnUIFirst.IsEnabled = true;
                            btnUILast.IsEnabled = true;
                            if (currentPage == countPages)
                            {
                                btnUINext.IsEnabled = false;
                                btnUILast.IsEnabled = false;
                            }
                            if (currentPage == 1)
                            {
                                btnUIPrev.IsEnabled = false;
                                btnUIFirst.IsEnabled = false;
                            }
                            btnUIEditDetail.IsEnabled = true;
                            btnUIRemove.IsEnabled = true;
                            btnUIPublish.IsEnabled = true;
                            txbUIPages.Text = "Page " + currentPage + " of " + countPages + " Pages of " + countImages + " Images";
                        }
                        else
                        {
                            btnUIEditDetail.IsEnabled = false;
                            btnUIRemove.IsEnabled = false;
                            btnUIPublish.IsEnabled = false;
                            btnUINext.IsEnabled = false;
                            btnUIPrev.IsEnabled = false;
                            btnUIFirst.IsEnabled = false;
                            btnUILast.IsEnabled = false;
                            txbUIPages.Text = "Page 0 of 0 Pages of 0 Images";
                        }
                    });
                }).Start();
        }

        //private bool isFinishEditing(int i)
        //{
        //    for (int j = i * 3; j < cbMainLanguage.Items.Count; j++)
        //        if (lUploadDImages[j].Name != "")
        //            return true;
        //    return false;
        //}


        private void btnUIUpload_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (cbUICategory.SelectedIndex < 0 || cbUISubCategory.SelectedIndex < 0)
            {
                errorList = new List<ErrorItem>();
                errorList.Add(new ErrorItem("Warning", "Please choose category."));
                MessageForm form = new MessageForm();
                form.UserRole = userRole;
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose category!";
                form.ShowDialog();
                return;
            }
            //for (int i = 0; i < lUploadImages.Count; i++)
            //{
            //    if (!isFinishEditing(i) || lUploadImages[i].Author == "" || lUploadImages[i].ID_City == 0)
            //    {
            //        el.Add(new ErrorItem("Warning", "Please fill out image information"));
            //        this.GetErrorList(el);
            //        return;
            //    }
            //}

            lblUIUploading.Content = "Uploading...";
            pbUIUpload.Minimum = 0;
            pbUIUpload.Maximum = lUploadImages.Count + 1;
            pbUIUpload.Value = 0;

            if (currentCategory != null)
            {
                errorList = new List<ErrorItem>();
                new Thread(
                       delegate()
                       {
                           Upload();
                           LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);

                           if (errorList.Count > 0)
                           {
                               Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                               {
                                   MessageForm form = new MessageForm();
                                   form.ErrorList = errorList;
                                   form.ShowDialog();
                               });
                           }
                           else
                           {
                               Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                               {
                                   errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));
                                   MessageForm form = new MessageForm();
                                   form.ErrorList = errorList;
                                   form.ShowDialog();
                               });
                           }
                       }).Start();
            }
        }

        private void Upload()
        {
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.IsEnabled = false; }, null);
            double value = 0;

            if (userRole.UserInfo.ID_Permission == 1)
            {
                OwnerRole role = (OwnerRole)userRole;
                for (int i = 0; i < lUploadImages.Count; i++)
                {
                    DetailImage di = new DetailImage();
                    di.ID_Language = 1;
                    di.Name = "";
                    di.Description = "";
                    di.Tag = "";
                    DetailUser du = userRole.UserInfo.GetDetail(userRole.ID_Language);
                    lUploadImages[i].Author = xmlHelper.ImageAuthor;
                    if (lUploadImages[i].Author == "")
                        lUploadImages[i].Author = du.Lastname + " " + du.Firstname;
                    Category c = currentCategory;
                    lUploadImages[i].ID_City = c.ID_City;
                    lUploadImages[i].TakenTime = c.TakenTime.Value;
                    errorList = role.UploadImage(lUploadImages[i], c.ID, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
                }
            }
            else if (userRole.UserInfo.ID_Permission == 4)
            {
                PartnerRole role = (PartnerRole)userRole;
                for (int i = 0; i < lUploadImages.Count; i++)
                {
                    DetailImage di = new DetailImage();
                    di.ID_Language = 1;
                    di.Name = "";
                    di.Description = "";
                    di.Tag = "";
                    DetailUser du = userRole.UserInfo.GetDetail(userRole.ID_Language);
                    lUploadImages[i].Author = du.Lastname + " " + du.Firstname;
                    Category c = currentCategory;
                    lUploadImages[i].ID_City = c.ID_City;
                    lUploadImages[i].TakenTime = c.TakenTime.Value;
                    errorList = role.UploadImage(lUploadImages[i], c.ID, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
                }
            }
            value++;
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Finish"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.IsEnabled = true; }, null);
        }

        private void btnUICancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            txtUIImages.Text = "";
            lUploadImages = null;
            pbUIUpload.Value = 0;
            lblUIUploading.Content = "";

            //List<ErrorItem> el = new List<ErrorItem>();
            //if (userRole.UserInfo.ID_Permission == 1)
            //{
            //    OwnerRole role = (OwnerRole)userRole;
            //    foreach (VietImage.Models.Image img in lUploadImages)
            //        el.=role.DeleteImage(img.ID, 0));
            //}
            //else if (userRole.UserInfo.ID_Permission == 4)
            //{
            //    PartnerRole role = (PartnerRole)userRole;
            //    foreach (VietImage.Models.Image img in lUploadImages)
            //        el.=role.DeleteImage(img.ID));
            //}
            //if (el.Count > 0)
            //    this.GetErrorList(el);
            //dgUIImagesList.DataContext = null;
            //lUploadImages = new List<VietImage.Models.Image>();
            //lUploadDImages = new List<DetailImage>();
            //txtUIImages.Text = "";
            //pbUIUpload.Value = 0;
            //lblUIUploading.Content = "";
            //cbUICategory.IsEnabled = true;
            //cbUISubCategory.IsEnabled = true;
        }

        private void btnUIRemove_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (dgUIImagesList.SelectedIndex >= 0)
            {
                errorList = new List<ErrorItem>();
                List<VietImage.Models.Image> l = new List<VietImage.Models.Image>();
                foreach (VietImage.Models.Image img in dgUIImagesList.SelectedItems)
                    l.Add(img);

                new Thread(
                    delegate()
                    {
                        Remove(l);
                        LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                    }).Start();

                if (errorList.Count > 0)
                {
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                    return;
                }
                else
                {
                    userRole.UserInfo = User.GetUser(userRole.UserInfo.ID);
                    errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                }
            }
        }

        private void Remove(List<VietImage.Models.Image> l)
        {
            double value = 0;
            double max = 1;
            if (l.Count > 0)
                max = l.Count + 1;
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, false); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Removing"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.MaximumProperty, max); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);

            foreach (VietImage.Models.Image img in l)
            {
                if (userRole.UserInfo.ID_Permission == 1)
                {
                    OwnerRole role = (OwnerRole)userRole;
                    errorList = role.DeleteImage(img.ID, 0);
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
                        return;
                    }
                }
                else if (userRole.UserInfo.ID_Permission == 4)
                {
                    PartnerRole role = (PartnerRole)userRole;
                    errorList = role.DeleteImage(img.ID);
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
                        return;
                    }
                }
                value++;
                Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
            }

            value++;
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Finish"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
        }

        private void dgUIImagesList_CellEditEnding(object sender, Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs e)
        {
            //if (dgUIImagesList.SelectedIndex >= 0)
            //{
            //    VietImage.Models.Image i = VietImage.Models.Image.Parse(e.Row.Item);
            //    if (i != null)
            //    {
            //        lUploadImages[dgUIImagesList.SelectedIndex] = i;
            //        idImageEditing = dgUIImagesList.SelectedIndex;
            //    }
            //}
        }

        private void dgUIImagesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (dgUIImagesList.SelectedIndex >= 0)
            //{
            //    currentImage = (VietImage.Models.Image)dgUIImagesList.SelectedItem;
            //    ManageImageForm form = new ManageImageForm();
            //    form.CurrentImage = currentImage;
            //    form.ShowDialog();
            //}
        }

        private void cbUICategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbUICategory.SelectedIndex >= 0)
            {
                DetailCategory c = (DetailCategory)cbUICategory.SelectedItem;
                currentCategory = c.Category;
                List<Category> dl = currentCategory.GetListAvailableChildren();
                cbUISubCategory.Items.Clear();
                if (dl != null)
                {
                    foreach (Category temp in dl)
                    {
                        if (!temp.IsParent)
                        {
                            DetailCategory dc = temp.GetDetail(int.Parse(cbMainLanguage.SelectedValue.ToString()));
                            cbUISubCategory.Items.Add(dc);
                        }
                    }
                    cbUISubCategory.SelectedValuePath = "ID_Category";
                    cbUISubCategory.DisplayMemberPath = "Name";
                    if (cbUISubCategory.Items.Count > 0)
                        cbUISubCategory.SelectedIndex = 0;
                }
            }
        }

        private void cbUISubCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbUISubCategory.SelectedIndex >= 0)
            {
                currentCategory = ((DetailCategory)cbUISubCategory.SelectedItem).Category;
                //VietImage.Models.Image img = currentCategory.PrimaryImage;

                if (userRole.UserInfo != null && gridUploadImages.IsVisible)
                {
                    currentPage = 1;
                    LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                }
            }
        }

        private void btnUIPublish_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            errorList = new List<ErrorItem>();

            //if (id_Image_Primary == 0)
            //{
            //    this.GetErrorList(new List<ErrorItem>() { new ErrorItem("Warning", "Please choose primary image") });
            //    return;
            //}

            new Thread(
            delegate()
            {
                Publish();
                LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                if (errorList.Count > 0)
                {
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                    return;
                }
                else
                {
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                    {
                        userRole.UserInfo = User.GetUser(userRole.UserInfo.ID);
                        errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                    });
                }
            }).Start();
        }

        private void btnUIUpdate_Click(object sender, RoutedEventArgs e)
        {
            errorList = new List<ErrorItem>();

            new Thread(
            delegate()
            {
                Update();

                if (errorList.Count > 0)
                {
                    MessageForm form = new MessageForm();
                    form.ErrorList = errorList;
                    form.ShowDialog();
                    return;
                }
                else
                {
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                    {
                        userRole.UserInfo = User.GetUser(userRole.UserInfo.ID);
                        errorList.Add(new ErrorItem("ErrorMessage", ErrorMessage.GetErrorMessage(1, userRole.ID_Language).Description));
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                    });
                }
            }).Start();
        }

        private void Publish()
        {
            double value = 0;
            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { 
				gridMain.SetValue(Grid.IsEnabledProperty, false); 
				lblUIUploading.SetValue(Label.ContentProperty, "Publishing"); 
				pbUIUpload.SetValue(ProgressBar.MaximumProperty, (double)(countImages + 1));
				pbUIUpload.SetValue(ProgressBar.ValueProperty, value);  
				dgUIImagesList.ItemsSource = null; });
            if (userRole.UserInfo.ID_Permission == 1)
            {
                OwnerRole role = (OwnerRole)userRole;
                int n = 0;
                List<VietImage.Models.Image> li = role.ViewNotPublishImages(currentCategory.ID, countImages, 0, out n);
                foreach (VietImage.Models.Image img in li)
                {
                    img.ID_Status = 1;
                    errorList = role.EditImage(img, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); });
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); });
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); });
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); });
                        return;
                    }
                }


            }
            else if (userRole.UserInfo.ID_Permission == 4)
            {
                PartnerRole role = (PartnerRole)userRole;
                int n = 0;
                List<VietImage.Models.Image> li = role.ViewNotPublishImages(currentCategory.ID, countImages, 0, out n);
                foreach (VietImage.Models.Image img in li)
                {
                    img.ID_Status = 1;
                    errorList = role.EditImage(img, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); });
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); });
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); });
                        Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); });
                        return;
                    }
                }
            }

            value++;
            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); });
            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Finish"); });
            Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); });
        }

        private void Update()
        {
            double value = 0;
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, false); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Updating"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.MaximumProperty, (double)(omUploadedImages.Count + 1)); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);

            if (userRole.UserInfo.ID_Permission == 1)
            {
                foreach (VietImage.Models.Image img in omUploadedImages)
                {
                    OwnerRole role = (OwnerRole)userRole;
                    errorList = role.EditImage(img, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
                        return;
                    }
                }
            }
            else if (userRole.UserInfo.ID_Permission == 4)
            {
                foreach (VietImage.Models.Image img in omUploadedImages)
                {
                    PartnerRole role = (PartnerRole)userRole;
                    errorList = role.EditImage(img, 0);
                    value++;
                    Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
                    if (errorList.Count > 0)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, 0.0); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, ""); }, null);
                        Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
                        return;
                    }
                }
            }

            value++;
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { pbUIUpload.SetValue(ProgressBar.ValueProperty, value); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { lblUIUploading.SetValue(Label.ContentProperty, "Finish"); }, null);
            Dispatcher.Invoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { gridMain.SetValue(Grid.IsEnabledProperty, true); }, null);
        }

        private void btnUIRefresh_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            new Thread(
                delegate()
                {
                    currentPage = 1;
                    LoadImagesList(userRole.UserInfo.ID_Permission, currentCategory.ID);
                }).Start();
        }

        private void txtUIImages_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (lnUploadImages != null)
                if (lnUploadImages.Count() != 0)
                    btnUIUpload.IsEnabled = true;
                else
                    btnUIUpload.IsEnabled = false;
            else
                btnUIUpload.IsEnabled = false;
        }

        private void dgUIImagesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            if (dgUIImagesList.SelectedIndex >= 0)
            {
                currentImage = ((VietImage.Models.Image)dgUIImagesList.SelectedItem).Clone();
                ManageImageForm form = new ManageImageForm();
                form.UserRole = userRole;
                form.CurrentImage = currentImage;
                form.SubCategoryName = cbUISubCategory.Text;
                form.ShowDialog();
            }
            else
            {
                errorList = new List<ErrorItem>();
                MessageForm form = new MessageForm();
                form.HaveOKButton = false;
                form.TxtTitle = "Warning";
                form.TxtCancel = "Cancel";
                form.TxtMessage = "Please choose image";
                form.ShowDialog();
            }
        }

        #endregion

        #region History
        int currentWeek;

        private void gridHistory_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (gridHistory.IsVisible)
            {

                int year = DateTime.Now.Year;

                if (cbHWWeek.Items.Count == 0)
                {
                    List<Week> lWeek = Week.ListWeeks(DateTime.Now.Year);

                    foreach (Week w in lWeek)
                    {
                        cbHWWeek.Items.Add(w);
                        if (w.BeginDate <= DateTime.Now && w.EndDate >= DateTime.Now)
                            currentWeek = w.Num;
                    }
                    cbHWWeek.SelectedValuePath = "Num";
                    cbHWWeek.DisplayMemberPath = "Description";
                }

                cbHMYear.Items.Clear();
                for (int i = 0; i < 5; i++)
                    cbHMYear.Items.Add(DateTime.Now.Year - i);
                cbHMYear.SelectedIndex = 0;
                cbHMMonth.SelectedIndex = DateTime.Now.Month - 1;

                cbHPrior.SelectedIndex = 0;
            }
        }

        private void LoadImagesList(int id_Permission)
        {
            new Thread(
                delegate()
                {
                    Dispatcher.Invoke(DispatcherPriority.Background, (System.Action)delegate
                    {
                        ProgressBarForm form = new ProgressBarForm();
                        form.CurrentPage = currentPage;
                        form.UserRole = userRole;
                        form.Prior = cbHPrior.SelectedIndex;
                        if (cbHPrior.SelectedIndex == 0)
                            if (dpHDDate.SelectedDate.HasValue)
                                form.CurrentDate = dpHDDate.SelectedDate.Value;
                            else
                                form.CurrentDate = DateTime.Now;
                        else if (cbHPrior.SelectedIndex == 1)
                            form.CurrentWeek = (Week)cbHWWeek.SelectedItem;
                        else if (cbHPrior.SelectedIndex == 2)
                        {
                            form.CurrentMonth = int.Parse(cbHMMonth.SelectedItem.ToString());
                            form.CurrentYear = int.Parse(cbHMYear.SelectedItem.ToString());
                        }
                        form.Id_Command = 8;
                        form.ShowDialog();
                        omHistoryImages = form.OmHistoryImages;
                        dgHImagesList.ItemsSource = omHistoryImages;
                        countPages = form.CountPages;
                        countImages = form.CountImages;
                        if (omHistoryImages.Count != 0)
                        {
                            btnHNext.IsEnabled = true;
                            btnHPrev.IsEnabled = true;
                            btnHFirst.IsEnabled = true;
                            btnHLast.IsEnabled = true;
                            if (currentPage == countPages)
                            {
                                btnHNext.IsEnabled = false;
                                btnHLast.IsEnabled = false;
                            }
                            if (currentPage == 1)
                            {
                                btnHPrev.IsEnabled = false;
                                btnHFirst.IsEnabled = false;
                            }
                            txbHPages.Text = "Page " + currentPage + " of " + countPages + " Pages of " + countImages + " Images";
                        }
                        else
                        {
                            btnHNext.IsEnabled = false;
                            btnHPrev.IsEnabled = false;
                            btnHFirst.IsEnabled = false;
                            btnHLast.IsEnabled = false;
                            txbHPages.Text = "Page 0 of 0 Pages of 0 Images";
                        }
                    });
                }).Start();
        }

        private void dgHImagesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dgHImagesList.SelectedIndex >= 0)
            {
                currentImage = ((VietImage.Models.Image)dgHImagesList.SelectedItem);
                ManageImageForm form = new ManageImageForm();
                form.UserRole = userRole;
                form.CurrentImage = currentImage;
                form.SubCategoryName = currentImage.Category.GetDetail(userRole.ID_Language).Name;
                form.Prior = cbHPrior.SelectedIndex;
                if (cbHPrior.SelectedIndex == 0)
                    if (dpHDDate.SelectedDate.HasValue)
                        form.CurrentDate = dpHDDate.SelectedDate.Value;
                    else
                        form.CurrentDate = DateTime.Now;
                else if (cbHPrior.SelectedIndex == 1)
                    form.CurrentWeek = (Week)cbHWWeek.SelectedItem;
                else if (cbHPrior.SelectedIndex == 2)
                {
                    form.CurrentMonth = (int)cbHMMonth.SelectedItem;
                    form.CurrentYear = (int)cbHMYear.SelectedItem;
                }
                form.ShowDialog();
            }
        }

        private void btnHRefresh_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            currentPage = 1;
            LoadImagesList(userRole.UserInfo.ID_Permission);
        }

        private void cbHPrior_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbHPrior.SelectedIndex >= 0)
            {
                switch (cbHPrior.SelectedItem.ToString())
                {
                    case "Daily":
                        {
                            dpHDDate.SelectedDate = DateTime.Now;
                            dpHDDate.Visibility = Visibility.Visible;
                            cbHWWeek.Visibility = Visibility.Hidden;
                            cbHMMonth.Visibility = Visibility.Hidden;
                            cbHMYear.Visibility = Visibility.Hidden;
                            lblHMMonth.Visibility = Visibility.Hidden;
                            lblHMYear.Visibility = Visibility.Hidden;
                            if (dgHImagesList.DataContext == null)
                            {
                                currentPage = 1;
                                LoadImagesList(userRole.UserInfo.ID_Permission);
                            }
                            break;
                        }
                    case "Weekly":
                        {
                            cbHWWeek.SelectedIndex = currentWeek - 1;
                            dpHDDate.Visibility = Visibility.Hidden;
                            cbHWWeek.Visibility = Visibility.Visible;
                            cbHMMonth.Visibility = Visibility.Hidden;
                            cbHMYear.Visibility = Visibility.Hidden;
                            lblHMMonth.Visibility = Visibility.Hidden;
                            lblHMYear.Visibility = Visibility.Hidden;
                            if (dgHImagesList.DataContext == null)
                            {
                                currentPage = 1;
                                LoadImagesList(userRole.UserInfo.ID_Permission);
                            }
                            break;
                        }
                    case "Monthly":
                        {
                            cbHMMonth.SelectedIndex = DateTime.Now.Month - 1;
                            cbHMYear.SelectedIndex = DateTime.Now.Year - int.Parse(cbHMYear.SelectedItem.ToString());
                            dpHDDate.Visibility = Visibility.Hidden;
                            cbHWWeek.Visibility = Visibility.Hidden;
                            lblHMMonth.Visibility = Visibility.Visible;
                            lblHMYear.Visibility = Visibility.Visible;
                            cbHMMonth.Visibility = Visibility.Visible;
                            cbHMYear.Visibility = Visibility.Visible;
                            if (dgHImagesList.DataContext == null)
                            {
                                currentPage = 1;
                                LoadImagesList(userRole.UserInfo.ID_Permission);
                            }
                            break;
                        }
                }
            }
        }

        private void dpHDDate_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbHPrior.SelectedIndex == 0 && dpHDDate.IsVisible)
            {
                currentPage = 1;
                LoadImagesList(userRole.UserInfo.ID_Permission);
            }
        }

        private void cbHWWeek_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbHPrior.SelectedIndex == 1 && cbHWWeek.SelectedIndex >= 0)
            {
                currentPage = 1;
                LoadImagesList(userRole.UserInfo.ID_Permission);

            }
        }

        private void cbHMMonth_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbHPrior.SelectedIndex == 2 && cbHMMonth.SelectedIndex >= 0 && cbHMYear.SelectedIndex >= 0)
            {
                currentPage = 1;
                LoadImagesList(userRole.UserInfo.ID_Permission);
            }
        }


        #endregion

        #region About Us
        #endregion
    }
}
